package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/csrf"
	"github.com/gorilla/mux"
	"net/http"
)

func main() {
	r := mux.NewRouter()
	csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))

	api := r.PathPrefix("/api").Subrouter()
	api.Use(csrfMiddleware)
	api.HandleFunc("/user/{id}", GetUser).Methods("GET")
	api.HandleFunc("/post-test", PostTest).Methods("POST")

	http.ListenAndServe(":8000", r)
}

// PostTest PostTest
func PostTest(w http.ResponseWriter, r *http.Request) {
	// csrfCookie, _ := r.Cookie("_gorilla_csrf")
	// fmt.Println(csrfCookie.Value)
	// fmt.Println(r.Header.Get("X-CSRF-Token"))
	w.Write([]byte("csrf token valid"))
}

// GetUser GetUser
// 响应信息：
// Set-Cookie: _gorilla_csrf=MTYwNDQwNzYxNXxJa1JESzBOaGR6RkNVRGQwTW1vdmFXTldiR2s1YVVwMVRtd3JTVWcxZWxoaVUyeHZUM1ZwUTJSWmQyTTlJZ289fMO4XG8AJlpPiQl86Unk7tSJymp0lom292Tf4FauBPzS; Expires=Wed, 04 Nov 2020 00:46:55 GMT; Max-Age=43200; HttpOnly; Secure; SameSite=Lax
// Vary: Cookie
// X-Csrf-Token: fWHMxAasS1JtVQxLtaLnTxs5wvUHIrkDkOFpmg+0WMdxTk6vC+106Rva9Nfj+lrHgLRVFwDFjNjau2cgLyk7wA==
func GetUser(w http.ResponseWriter, r *http.Request) {
	// Authenticate the request, get the id from the route params,
	// and fetch the user from the DB, etc.

	// Get the token and pass it in the CSRF header. Our JSON-speaking client
	// or JavaScript framework can now read the header and return the token in
	// in its own "X-CSRF-Token" request header on the subsequent POST.
	if csrfCookie, err := r.Cookie("_gorilla_csrf"); err == nil {
		fmt.Println(csrfCookie.Value)
	}
	fmt.Println(r.Header.Get("X-CSRF-Token"))
	w.Header().Set("X-CSRF-Token", csrf.Token(r))
	user := "{\"name\":\"Mike\"}"
	b, err := json.Marshal(user)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	w.Write(b)
}
